package com.pushtalk.utils;

import java.util.Date;

import org.apache.log4j.Logger;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.receipts.DeliveryReceiptManager;

import com.pushtalk.Config;
import com.pushtalk.MainPush;
import com.pushtalk.entity.BussNotify;

public class IMUtil {
	
	private static Logger logger  =  Logger.getLogger(IMUtil.class);
	private static org.jivesoftware.smack.XMPPConnection connection;
	private static String jid;
	
	public static XMPPConnection loginXMPP(String username, String password) {		

		try {
			if (Config.RunningEnvironment.equals("Test")) {
				connection = new XMPPConnection(Config.ImHostTest);
				connection.connect();
				connection.login(username + Config.JIDTest, password);
				jid = Config.JIDTest;
			} else if (Config.RunningEnvironment.equals("Production")) {
				connection = new XMPPConnection(Config.ImHostPro);
				connection.connect();
				connection.login(username + Config.JIDPro, password);
				jid = Config.JIDPro;
			} else {
				connection = new XMPPConnection(Config.ImHostDebug);
				connection.connect();
				connection.login(username + Config.JIDDebug, password);
				jid = Config.JIDDebug;
			}
			
			return connection;

		} catch (XMPPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e);
		}
	
		return null;
	}
	
	public static boolean SendToIM(BussNotify bn) {
		org.jivesoftware.smack.ChatManager chatmanager = connection
				.getChatManager();
		org.jivesoftware.smack.Chat newChat = chatmanager.createChat(bn.getUsername()+jid,
				new MessageListener() {
					public void processMessage(Chat chat, Message message) {
						// 消息处理
					}
				});
		try {
			Message message = new Message();
			message.setBody(bn.getSubject());
			message.setProperty("date", new Date());
			message.setProperty("push", true);
			DeliveryReceiptManager.addDeliveryReceiptRequest(message);
			newChat.sendMessage(message);
			
			return true;
		} catch (XMPPException e) {
			logger.error(e);
			return false;
		}
	}

}
